package com.bookshop.servlet;

import com.bookshop.entity.Book;
import com.bookshop.service.BookService;
import com.bookshop.service.impl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(urlPatterns = {"/book"})
public class BookServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        BookService bookService = new BookServiceImpl();
        //获取请求的类型参数 action=list,action=details,action=add,action=edit,action=delete
        String action = request.getParameter("action");
        if (action == null || "list".equals(action)) {//查询
            List<Book> books = bookService.findBooksByCount(16);
            //将查询到的图书列表存储在request作用域
            request.setAttribute("books", books);
            //跳转到图书首页
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } else if ("details".equals(action)) {//查询详情
            //根据图书编号查询图书对象
            Integer id = Integer.valueOf(request.getParameter("id"));
            //将查询到的图书对象存储到request
            Book book = bookService.findById(id);
            request.setAttribute("book", book);
            //转发
            request.getRequestDispatcher("details.jsp").forward(request, response);
        }

    }
}
